package com.credithc.eagleeye.spring.starter;
import com.credithc.eagleeye.plugins.rest.EagleEyeRestTemplateInterceptor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
/**
 * 描 述: <br/>
 * 作 者: zhangjin<br/>
 * 创 建：2019年10月28日<br/>
 * 版 本：v1.0.0<br>
 * <p>
 * 历 史: (版本) 作者 时间 注释 <br/>
 */
@Configuration
@AutoConfigureAfter({EagleEyeAgentAutoConfiguration.class})
@ConditionalOnClass(name = {"org.springframework.web.client.RestTemplate"})
public class EagleEyeRestTemplateAutoConfiguration {
    @Bean
    @ConditionalOnMissingBean(RestTemplate.class)
    public RestTemplate eagleEyeRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate;
    }

    @Bean
    @ConditionalOnMissingBean
    static EagleEyeRestTemplateBeanPostProcessor eagleEyeRestTemplateBeanPostProcessor() {
        return new EagleEyeRestTemplateBeanPostProcessor();
    }
}

class EagleEyeRestTemplateBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        if (bean instanceof RestTemplate) {
            RestTemplate restTemplate = (RestTemplate) bean;
            ClientHttpRequestInterceptor eagleEyeRestTemplateInterceptor = new EagleEyeRestTemplateInterceptor();
            restTemplate.setInterceptors(Collections.singletonList(eagleEyeRestTemplateInterceptor));
            return restTemplate;
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}
